package com.apes.fn.scm.retailOrder.service.retailProcess.process;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.contract.FnContract;
import com.apes.fn.scm.contract.FnContractRepository;
import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.service.retailProcess.CommonRetailDataProcess;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.contract.service.ContractService;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * 新能源电池检测报告
 *
 * 控制逻辑：APP 需要传入 商品明细上面的供应商字段，并且年审单据的商品规则字段为 10(代销带安逻辑)
 *
 * @author wuq
 * @create 2021-05-21 17:00
 */
@Service
public class DetectReportProcess extends CommonRetailDataProcess {

    @Autowired
    private ContractService contractService;

    @Override
    public void beforeSave(RetailOrder retailOrder) {
        // 获取年审价格的成本
        beforeProcess(retailOrder, this::getProductCostPrice);
    }

    private void getProductCostPrice(RetailOrder retailOrder) {

        retailOrder.getSaleItems().forEach(
                retailOrderItem -> {
                    // 设置 productRule, 年审默认的设置为 10
                    retailOrderItem.setProductRule(10);

                    // 获取平台公司
                    PartyRole platformCompany = getPlatFormCompany(retailOrder.getCompany());
                    retailOrderItem.setPlatform(platformCompany);
                    retailOrderItem.setOriginSupplier(retailOrderItem.getSupplier());   // 设置原始供应商

                    // 取平台的条件策略
                    Map strategyParam = MapUtil.mapper("conditionStrategyId", "CG01", "PRODUCT_ID", retailOrderItem.getProduct().getId(),
                            "CLASSIFY_ID", retailOrderItem.getProduct().getClassify().getId(),
                            "SYS_RQ", new Date(), "SUPPLIER_ID", retailOrderItem.getSupplier().getId(), "COMPANY_ID", platformCompany.getId());
                    Object obj = invoke("condition.execConditionStrategy", strategyParam);
                    JSONObject result = new JSONObject(MapUtil.mapped(obj));

                    if (result.getDouble("P001") == 0) {
                        throw new RuntimeException("电池检测报告订单无成本，请联系相关人员定义，商品名称：" + retailOrderItem.getProduct().getName());
                    }

                    // 设置对应的价格
                    retailOrderItem.setInnerSalePriceUnit(result.getDouble("F002"));
                    retailOrderItem.setPriceOutUnitInTax(result.getDouble("P001"));

                    // 1001 单独处理，1001 直接找供应商采购
                    if ("1001".equals(retailOrder.getCompany().getId())) {
                        retailOrderItem.setInnerSalePriceUnit(result.getDouble("P001"));
                    }

                    // 这里增加合同，后面走代销带安的逻辑
                    Contract contract = contractService.getContract(getDept(), retailOrderItem.getSupplier(),
                            "consignment", "supplier", "零售检测报告业务");
                    retailOrderItem.setContract(contract);
                });
    }

    private PartyRole getPlatFormCompany(PartyRole partyRole) {
        ArrayList rows = new ArrayList();
        rows.add(MapUtil.mapper("field", "state", "operator", "EQ", "value", "approve"));
        rows.add(MapUtil.mapper("field", "validPeriod", "operator", "GT", "value", new Date()));
        rows.add(MapUtil.mapper("field", "partner.id", "operator", "EQ", "value", partyRole.getId()));
        FnContract contract = SpringManager.getBean(FnContractRepository.class).findAll(JpaDsl.toCriteria(rows)).stream().findFirst().orElse(null);
        if (contract == null) {
            // 2022-01-05 按照老胡要求，取不到值的情况下，就默认 1001，后期业务出现错误数据，调整不管
            return SpringManager.getBean(PartyRoleRepository.class).findOne("1001");
        }
        return contract.getCompany();
    }

    private Dept getDept() {
        PartyRole company = SpringManager.getBean(PartyRoleRepository.class).findOne("1001");
        return SpringManager.getBean(DeptRepository.class)
                .findAll(JpaDsl.toCriteriaByEq("company", company, "innerTag", true, "deptType.id", "000006"))
                .stream().findFirst().orElseThrow(() -> new RuntimeException("没有找到内定标记部门，请先定义！公司：：" + company.getId()));
    }

    @Override
    public void afterSave(RetailOrder retailOrder) {
    }

    @Override
    public boolean support(String orderType) {
        return "detectReport".equals(orderType);
    }

}
